package org.wattdepot.cli.command;

import java.util.ArrayList;
import java.util.List;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Get the list of subsources of a given source using a given fueltype. 
 * 
 * @author Kendyll Doi
 * @author Kimberly Heu
 *
 */
public class WattSubsourcesFuel {
  
  /**
   * Gets the list of subsources of the given source using the specified fueltype.
   * 
   * @param source The source to check
   * @param fuelType The fueltype to check for; must match key used in Source declaration
   * @param client The WattDepotClient used for the sources
   * @return A List containing all subsources matching the criteria
   */
  public static List<String> getSubsourcesFuel (Source source, String fuelType, 
      WattDepotClient client) {
    
    List<String> fuelSourcesList = new ArrayList<String>(); // String of sources to return
    
    try {
      if (source.isVirtual()) {
        // If the source is virtual, get all subsources and call this method recursively.
        List<String> urlList = source.getSubSources().getHref();
        for (String url : urlList) {
          String modUrl = url.substring(url.lastIndexOf('/') + 1, url.length());
          fuelSourcesList.addAll(getSubsourcesFuel(client.getSource(modUrl), fuelType, client));
        }
      }
      else {
        // If source is nonvirtual, check fueltype and include name if necessary
        if (source.getProperty("fuelType").equals(fuelType)) {
          fuelSourcesList.add(source.getName());
        }
      }
    }
    catch (MiscClientException mcme) {
      mcme.printStackTrace();
      return null;
    }
    catch (NotAuthorizedException e) {
      e.printStackTrace();
      return null;
    }
    catch (ResourceNotFoundException e) {
      e.printStackTrace();
      return null;
    }
    catch (BadXmlException e) {
      e.printStackTrace();
      return null;
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    
    // Return the desired information
    return fuelSourcesList;
  }
}
